package com.xy.controller;

import ch.qos.logback.core.util.StringCollectionUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author xxy
 * @date 2022/1/7 14:17
 */
@RestController
@Slf4j
@RequestMapping("/use-redis")
public class UseRedisCacheController {


    private final StringRedisTemplate stringRedisTemplate;

    public UseRedisCacheController(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }


    @GetMapping("/test-cache")
    public Object testUseRedisCache() {
        // 初始化 redis 组件
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        // 从缓存中查询数据
        String dataList = ops.get("dataList");
        // 缓存中没有
        if (!StringUtils.hasText(dataList)) {
            log.info("the cache is empty!");
            // 查询数据库
            List<String> list = dataList();
            // 将数据库查询的数据序列化json字符串
            dataList = JSONUtil.toJsonStr(list);
            // 将序列化的数据放入缓存中
            ops.set("dataList", dataList, 10, TimeUnit.SECONDS);
        }
        log.info("dataList -> {}", dataList);
        return dataList;
    }


    private List<String> dataList() {
        List<String> dataList = new ArrayList<>();
        String[] data = {"a", "b", "c"};
        List<String> list = Arrays.asList(data);
        dataList.addAll(list);
        return dataList;
    }


}
